<template>
  <view class="drawing-board">
    <view class="canvas-box">
      <canvas
        canvas-id="handwritingCanvas"
        @touchstart="start"
        @touchmove="move"
        @touchend="end"
      ></canvas>
    </view>

    <view class="action">
      <button class="but clear" @click="clear">清除</button>
      <button class="but close" @click="close">关闭</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'

const emits = defineEmits(['close'])

const isMove = ref(false)
const content = ref()
let touchs = ref<any[]>([])
onMounted(() => {
  content.value = uni.createCanvasContext(
    'handwritingCanvas',
    getCurrentInstance(),
  )
  //设置线的颜色
  content.value.setStrokeStyle('#000000')
  //设置线的宽度
  content.value.setLineWidth(3)
  //设置线两端端点样式更加圆润
  content.value.setLineCap('round')
  //设置两条线连接处更加圆润
  content.value.setLineJoin('round')
})

// 画布的触摸移动开始手势响应
const start = (event: any) => {
  let point = {
    x: event.changedTouches[0].x,
    y: event.changedTouches[0].y,
  }
  touchs.value.push(point)
}
// 画布的触摸移动手势响应
const move = (e: any) => {
  let point = {
    x: e.touches[0].x,
    y: e.touches[0].y,
  }
  touchs.value.push(point)
  if (touchs.value.length >= 2) {
    isMove.value = true
    draw(touchs)
  }
}
// 画布的触摸移动结束手势响应
const end = (e: any) => {
  console.log('触摸结束' + e)
  touchs.value = []
  isMove.value = false
}

//绘制
const draw = (t: any) => {
  let point1 = t.value[0]
  let point2 = t.value[1]
  touchs.value.shift()
  content.value.moveTo(point1.x, point1.y)
  content.value.lineTo(point2.x, point2.y)
  content.value.stroke()
  content.value.draw(true)
}

//清除操作
const clear = () => {
  const windowsH = uni.getSystemInfoSync().windowHeight
  const windowsW = uni.getSystemInfoSync().windowWidth
  content.value.clearRect(0, 0, windowsW, windowsH)
  content.value.draw(true)
  isMove.value = false
}

const close = () => {
  clear()
  emits('close')
}
</script>

<style lang="scss" scoped>
.drawing-board {
  width: 100%;
  height: 100vh;

  .canvas-box {
    width: 100%;
    height: calc(100% - 120rpx);

    > canvas {
      width: 100%;
      height: 100%;
    }
  }

  .action {
    width: 100%;
    height: 120rpx;
    background-color: #fff;
    display: flex;
    align-items: center;

    .but {
      width: 150rpx;
      color: #fff;
      border-radius: 50rpx;
    }

    .clear {
      background-color: #fc5531;
    }
    .close {
      background-color: #367cf1;
    }
  }
}
</style>
